package com.kx.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.kx.base.controller.BaseController;
import com.kx.base.dto.face.FaceDTO;
import com.kx.base.dto.file.QRCodeDTO;
import com.kx.base.dto.file.ZoomDTO;
import com.kx.base.dto.sms.SmsDTO;
import com.kx.base.dto.user.UserInfosDTO;
import com.kx.base.result.R;
import com.kx.base.util.JWTUtil;
import com.kx.base.util.PropertiesUtil;
import com.kx.base.vo.UserVO;
import com.kx.user.client.FaceClient;
import com.kx.user.client.FileClient;
import com.kx.user.client.SmsClient;
import com.kx.user.dto.*;
import com.kx.user.pojo.User;
import com.kx.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author Sun
 * @Date 2021/7/16 14:04
 */
@RestController
@RequestMapping("kx/user")
public class UserController extends BaseController {

    @Autowired
    private Random random;

    @Autowired
    private SmsClient smsClient;

    @Autowired
    private UserService userService;

    @Resource
    private FaceClient faceClient;

    @Autowired
    private FileClient fileClient;

    @GetMapping("test")
    public R test() {
        UserVO userVO = user();
        Long userId = userId();
        System.out.println(userId);
        System.out.println(userVO);
        return R.ok().setResult(userVO);
    }

    @PostMapping("signin")
    public R signIn(@RequestBody SignInDTO signInDTO) {
        String signName = signInDTO.getSignName();
        String password = signInDTO.getPassword();
        //判断账户是否被锁定
        User user = userService.isLocked(signName);
        if (user == null) {
            return R.error("用户名不存在");
        }
        if (user.getIsLocked() == 1) {
            return R.error(501, "当前账号已经被锁定！");
        }

        user = userService.signIn(signName, password);

        if (user == null) {
            return R.error("用户名或者密码错误");
        } else {
            //使用JWT实现登录功能
            UserVO userVO = new UserVO();
            //对象转换user-->userVO
            PropertiesUtil.copy(user, userVO);
            //将密码置空
            userVO.setPassword("");
            //创建token
            String token = JWTUtil.generatorToken(userVO.getNickname(), userVO);
            //将userVO(没有密码)的token返回给前端
            JSONObject result = new JSONObject();
            result.put("token", token);
            result.put("user", userVO);
            return R.ok("登陆成功").setResult(result);
        }
    }

    /**
     * 请求验证码
     */
    @PostMapping("sms")
    public R sms(@RequestBody SmsDTO smsDTO) {
        //设置模块id
        smsDTO.setTypeId(1);
        //生成六位数验证码
        String code = "";
        for (int i = 0; i < 6; i++) {
            code = code + random.nextInt(10);
        }
        smsDTO.setCode(code);
        return smsClient.send(smsDTO);
    }

    /**
     * 前端输入邮箱、电子邮件、用户名的时候，应该实时提示是否重复
     */
    @PostMapping("checkinfo")
    public R checkInfo(@RequestBody CheckInfoDTO checkInfoDTO) {
        String info = checkInfoDTO.getInfo();
        Integer type = checkInfoDTO.getType();
        int result = userService.selectInfo(info, type);
        if (result > 0) {
            return R.error(500, "数据已经存在");
        } else {
            return R.ok(200, "数据可以使用");
        }
    }

    /**
     * 注册接口
     */
    @PostMapping("signup")
    private R signUp(@RequestBody SignUpDTO signUpDTO) {
        String code = signUpDTO.getCode();
        String phone = signUpDTO.getTelephone();
        Integer typeId = 1;
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setPhone(phone);
        smsDTO.setCode(code);
        smsDTO.setTypeId(typeId);
        //校验短信内容
        R check = smsClient.check(smsDTO);
        if (!check.isOK()) {
            return check;
        } else {
            //校验通过,把用户信息保存到数据库
            int result = userService.signUp(signUpDTO);
            if (result > 0) {
                return R.ok(200, "注册成功");
            } else {
                return R.ok(500, "注册失败");
            }
        }
    }

    /**
     * 手机号一键登录
     */
    @PostMapping("onekeysignin")
    public R oneKeySignIn(@RequestBody OneKeySignInDTO oneKeySignInDTO) {
        String phone = oneKeySignInDTO.getPhone();
        String code = oneKeySignInDTO.getCode();
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setPhone(phone);
        smsDTO.setCode(code);
        smsDTO.setTypeId(1);

        //校验验证码是否正确
        R check = smsClient.check(smsDTO);
        if (!check.isOK()) {
            return check;
        } else {
            //校验成功
            //将用户信息存入数据库中，然后将用户信息查询出来
            User user = userService.oneKeySignIn(phone);
            UserVO userVO = new UserVO();
            //将密码置空
            userVO.setPassword("");
            //user->userVO
            PropertiesUtil.copy(user, userVO);

            //生成Token
            String token = JWTUtil.generatorToken(user.getNickname(), userVO);
            //将不带密码的userVO和Token返回给前端
            JSONObject result = new JSONObject();
            result.put("token", token);
            result.put("user", userVO);
            return R.ok(result);
        }
    }

    /**
     * 用户录入人脸信息
     */
    @PutMapping("face")
    public R uploadFace(@RequestBody UserFaceDTO userFaceDTO) {
        String base64 = userFaceDTO.getFaceBase64();
        Long userId = userId();
        if (userId == null) {
            return R.error(501, "请先登录");
        }
        //调用人脸服务
        FaceDTO faceDTO = new FaceDTO();
        faceDTO.setUserId(userId);
        faceDTO.setFace(base64);
        faceDTO.setServiceId(1);
        R result = faceClient.save(faceDTO);
        if (result.isOK()) {
            return R.ok(200, "人脸录入成功");
        } else {
            return R.error(500, "人脸录入失败");
        }
    }

    /**
     * 用户识别人脸信息进行登陆
     */
    @PostMapping("face")
    public R faceSignIn(@RequestBody UserFaceDTO userFaceDTO) {
        String base64 = userFaceDTO.getFaceBase64();
        //调用人脸服务
        FaceDTO faceDTO = new FaceDTO();
        faceDTO.setFace(base64);
        faceDTO.setServiceId(1);
        R faceResult = faceClient.search(faceDTO);
        if (faceResult.isOK()) {
            //拿到用户的id
            Long userId = Long.parseLong(((HashMap) (faceResult.getResult())).get("userId") + "");
            //找到对应的user
            User user = userService.searchUserById(userId);
            //签发token
            //User对象->UserVO对象
            //对象复制问题
            UserVO userVO = new UserVO();
            PropertiesUtil.copy(user, userVO);
            //把密码清空
            userVO.setPassword("");

            //签发token
            String token = JWTUtil.generatorToken(userVO.getNickname(), userVO);
            //token、userVO（不带密码的）返回给前端
            JSONObject result = new JSONObject();
            result.put("token", token);
            result.put("user", userVO);
            return R.ok(200, "登录成功");
        } else {
            return R.error(500, "登录失败");
        }
    }

    /**
     * 用户上传头像功能
     */
    @PostMapping("icon")
    public R icon(@RequestBody IconDTO iconDTO) {
        //获取已经登录的用户id
        Long userId = userId();
        String base64 = iconDTO.getBase64();
        ZoomDTO zoomDTO = new ZoomDTO();
        zoomDTO.setBase64(base64);
        zoomDTO.setWidth(200);
        zoomDTO.setHeight(200);
        zoomDTO.setTitle("");
        R fileResult = fileClient.uploadZoomImage(zoomDTO);
        if (fileResult.isOK()) {
            //操作数据库，把url保存至数据库
            JSONObject result = new JSONObject((Map<String, Object>) fileResult.getResult());
            String url = (String) result.get("url");
            int r = userService.updateIconLinkById(userId, url);
            if (r > 0) {
                return R.ok(200,"头像保存成功");
            } else {
                return R.error(500,"头像保存失败");
            }
        } else {
            //文件上传失败
            return R.error(500,"头像保存失败");
        }
    }

    /**
     * 展示用户二维码名片
     */
    @GetMapping("myinfo")
    public R myInfo(){
        Long userId=userId();
        JSONObject contentObject=new JSONObject();
        contentObject.put("userId",userId);
        String content=contentObject.toJSONString();
        QRCodeDTO qrCodeDTO=new QRCodeDTO();
        qrCodeDTO.setContent(content);
        qrCodeDTO.setWidth(200);
        qrCodeDTO.setHeight(200);
        qrCodeDTO.setCodeColor("#000000");
        qrCodeDTO.setBgColor("#FFFFFF");
        R fileResult = fileClient.qrCode(qrCodeDTO);
        return fileResult;
    }

    /**
     * 查询单个用户信息
     */
    @PostMapping("userinfo")
    public R queryUserInfo(@RequestBody UserInfoDTO userInfoDTO){
        Long userId = userInfoDTO.getUserId();
        User user = userService.searchUserById(userId);
        UserVO userVO = new UserVO();
        PropertiesUtil.copy(user, userVO);
        userVO.setPassword("");
        return R.ok(200,"查询成功").setResult("user", userVO);
    }

    /**
     * 查询多个用户信息
     */
    @PostMapping("userinfos")
    public R queryUserInfos(@RequestBody UserInfosDTO userInfoDTOs){
        List<Long> userIds = userInfoDTOs.getUserIds();
        List<UserVO> userVOS = userService.searchUserByIds(userIds);
        return R.ok(200,"查询成功").setResult("users",userVOS);
    }
}
